package admin;

import play.db.jpa.Model;
import utils.RandomNumberUtil;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "admin_user_login_token")
public class AdminUserLoginToken extends Model {

    /**
     *  登录  员工
     */
    @ManyToOne
    @JoinColumn(name = "admin_user_id")
    public AdminUser adminUser;

    /**
     * toke
     */
    @Column(name="token")
    public String token ;

    @Column(name = "uuid")
    public String uuid;

    /**
     * 随机数
     */
    @Column(name = "random_number")
    public String randomNumber;

    /**
     * 失效时间
     */
    @Column(name="expire_at")
    public Date expireAt ;

    /**
     * 创建时间
     */
    @Column(name="created_at")
    public Date createdAt = new Date();


    /**
     * 生成token
     *
     * @return
     */
    public static String createToken(){
        String token = RandomNumberUtil.generateRandomNumberString(16) ;
        AdminUserLoginToken terminalLoginToken = AdminUserLoginToken.checkToken(token);
        if(terminalLoginToken != null){
            createToken();
        }

        return  token ;

    }

    /**
     * 根据UUID 查询token
     * @param uuid
     * @return
     */
    public static AdminUserLoginToken findByUUID(String uuid) {
        return AdminUserLoginToken.find("uuid = ?1" , uuid).first();
    }

    /**
     * 按照token插叙
     * @param token
     * @return
     */
    public static AdminUserLoginToken checkToken( String token){
        return  AdminUserLoginToken.find("token = ?1" , token).first();
    }


    /**
     * 根据token 查询
     * @param token
     * @return
     */
    public static AdminUserLoginToken findByToken(String token){
        Date nowTime = new Date();
        AdminUserLoginToken loginToken = AdminUserLoginToken.find(" token = ?1 and  expireAt > ?2"  , token , nowTime).first();
        if(loginToken == null) return  null ;

        return  loginToken ;
    }

    /**
     * a按照用户查询
     * @param userId
     * @return
     */
    public static AdminUserLoginToken findByUser(long userId){
        return  AdminUserLoginToken.find("terminalUser.id = ?1" ,userId).first();
    }

    /**
     * 查询有效登录用户
     * @param userId
     * @param token
     * @return
     */
    public static AdminUserLoginToken findByuserAndToken(long userId , String token){
        Date nowTime = new Date();
        AdminUserLoginToken loginToken = AdminUserLoginToken.find("terminalUser.id = ?1 and token = ?2 and  expireAt > ?3" , userId , token , nowTime).first();
        if(loginToken == null) return  null ;

        return  loginToken ;
    }
}
